<template>
	<view class="bgw">
		<view class="item">
			<view class="flex">
				<view class="" style="width: 16%;" v-if="table_hd.cost_category_id">
					{{detail.cost_category_id[1]}}
				</view>
				<view class="flex-1 text-center ml15 mr15" v-if="readonly && table_hd.cost_amount">
					<view class="flex" @click="openCostRecord">
						<view class="flex-1">
							{{detail.cost_amount}}
						</view>
						<view class="list-btn">
							<u-icon name="file-text" color="#675f91" size="16"></u-icon>
						</view>
					</view>

				</view>
				<view class="flex-1 text-center ml15 mr15" v-if="!readonly && isCanFastInput && table_hd.cost_amount">
					<view class="flex">
						<view class="flex-1">
							<input v-model="value" type="digit" placeholder="请输入" @blur="value_blur" @input="value_input" :maxlength="6"
								class="input_border_bottom" :class="errorTip?'input_border_bottom_red':''" />
						</view>
						<view class="list-btn" @click="openCostRecord">
							<u-icon name="file-text" color="#675f91" size="16"></u-icon>
						</view>
					</view>
				</view>
				<view class="flex-1 text-center ml15 mr15" v-if="!readonly && !isCanFastInput && table_hd.cost_amount" @click="openCostRecord">
					<view class="flex">
						<view class="flex-1">
							<view class="input_border_bottom" :class="errorTip?'input_border_bottom_red':''">
								{{detail.cost_amount}}
							</view>
						</view>
						<view class="list-btn">
							<u-icon name="file-text" color="#675f91" size="16"></u-icon>
						</view>
					</view>
				</view>
				<view class="text-center text-ellipsis" style="width: 20%;" v-if="table_hd.cost_ratio">
					{{detail.cost_ratio | filterRatio}}
				</view>
				<view class="text-center text-ellipsis" style="width: 20%;"  v-if="table_hd.month_cost_ratio">
					{{detail.month_cost_ratio | filterRatio}}
				</view>
				<!-- 操作 -->
				<view style="width: 20px">
					<view class="flex-1 flex" style="justify-content: center;" v-if="loading">
						<u-loading-icon size="16"></u-loading-icon>
					</view>
				</view>
				<!-- <view style="width: 15%;"  v-if="!readonly && detail.list.length == 1">
					<view class="flex">
						<view class="flex-1 flex" style="justify-content: center;" v-if="detail.note" @click="show = !show">
							<u-icon name="more-dot-fill" color="#675f91" size="16"></u-icon>
						</view>
						<view class="flex-1 flex" style="justify-content: center;" v-if="!detail.note" @click="show = !show">
							<u-icon name="edit-pen" color="#675f91" size="16"></u-icon>
						</view>
						<view class="flex-1 flex" style="justify-content: center;" v-if="!loading">
							<u-icon name="trash" color="#E40A0C" size="16" @click="bindDel"></u-icon>
						</view>
						<view class="flex-1 flex" style="justify-content: center;" v-if="loading">
							<u-loading-icon size="16"></u-loading-icon>
						</view>
					</view>
				</view>
				<view style="width: 15%;" v-if="readonly || detail.list.length>1">
					<view class="flex" style="justify-content: center;" v-if="detail.note" @click="show = !show">
						<u-icon name="more-dot-fill" color="#675f91" size="16"></u-icon>
					</view>
				</view> -->
				<!-- 操作 end-->
			</view>
		</view>
		<view class="text-red flex" style="padding: 0 20upx 10upx 20upx;" v-show="errorTip">
			<u-icon name="close-circle" color="#D6251F" size="14" class="mr10"></u-icon>
			<text>{{errorTip}}</text>
		</view>
		<view class="wrapper" v-show="show && !readonly">
			<view class="flex">
				<view class="flex-1">
					<u--textarea v-model="textarea_value" placeholder="请输入说明" autoHeight count border="bottom"
						@blur="textarea_value_blur"></u--textarea>
				</view>
				<!-- <view class="ml10">
					<u-button type="primary" size="mini" text="完成" @click="confirm"></u-button>
				</view> -->
			</view>
			<view class="blank20"></view>
		</view>
		<view class="wrapper" v-show="show && readonly">
			<view class="bg-gray wrapper">
				<view class="blank20"></view>
				<view class="flex">
					<text class="font-24 text-gray">说明：</text>
					<text class="">{{textarea_value}}</text>
				</view>
				<view class="blank20"></view>
			</view>

		</view>
		<u-line dashed></u-line>
	</view>
</template>

<script>
	const formatPrice = (price) => {
		price = '' + price;
		price = price
			.replace(/\s*/g, "") //去除字符串内所有的空格
			.replace(/[^\-\d.]/g, '') // 清除“-”“数字”和“.”以外的字符
			.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
			.replace('.', '$#$')
			.replace(/\./g, '')
			.replace('$#$', '.')
			.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
		// if (price.indexOf('.') < 0 && price != '') {
		//     // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
		//     price = parseFloat(price);
		// }
		// if (price[0] == '0' && price != '') {
		//     // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
		//     price = parseFloat(price);
		// }
		if (price != '') {
			price = Number(price);
		}
		return price;
	};
	import {
		one_day_kpi_report_detail,
		save_one_day_sales_cost_detail,
		update_cost_report_data,
		common_write,
		common_create,
		common_delete
	} from '@/common/api.js';
	export default {
		name: "cost-item",
		props: {
			detail: Object,
			readonly: Boolean,
			date: String,
			table_hd:Object,
			// modelname:String,
			month_sales_amount: Number,
			day_sales_amount: Number
			// :month="month_sales_amount" :day="day_sales_amount"
		},
		data() {
			return {
				// id: this.detail.id,
				show: false,
				value: this.detail.cost_amount,
				info: '',
				textarea_value: this.detail.note ? this.detail.note : '',
				loading: false,
				max_cost: 0,
				errorTip: ''
			};
		},
		watch: {
			detail: {
				handler(newVal, oldVal) {
					if (newVal.id != oldVal.id) {
						this.init();
					}
				},
				immediate: false,
				deep: true
			},
			value(newVal, oldVal) {
				let num = Number(newVal) || 0;
				if (Number(num) < 0) {
					this.errorTip = '金额不得小于0';
				} else if (this.max_cost && num > this.max_cost) {
					this.errorTip = '超出最大值' + this.max_cost;
				} else {
					this.errorTip = ''
				}
				this.set_ratio(num);
			},
			month_sales_amount(){
				this.set_ratio(this.detail.cost_amount);
			},
			day_sales_amount(){
				this.set_ratio(this.detail.cost_amount);
			}
		},
		created() {
			let userInfo = this.$store.getters.get_userInfo;
			this.max_cost = userInfo['通用配置'].max_cost || 0;
			this.init();

		},
		filters: {
			filterRatio(v) {
				if (!v) {
					return v;
				}
				let num = v * 100;
				return formatPrice(num) + '%'
			}
		},
		computed: {
			// 是否支持快速修改
			isCanFastInput(cost_category_id, date) {
				let daily_cost_record = this.detail.list;
				let readonly_daily_cost_record = daily_cost_record.filter(v => v.cost_classfication != 'manual_input' && v
					.cost_classfication != 'am' && v.cost_classfication != 'dp');

				if (readonly_daily_cost_record.length > 0) {
					return false;
				}
				if (daily_cost_record.length > 1) {
					return false;
				}
				if (daily_cost_record.length == 1) {
					return true;
				}
				// 无数据
				// let {
				// 	rel_partner_ids,
				// 	cost_classfication,
				// 	name
				// } = this.daily_cost_category[cost_category_id];
				// let is_amdp = cost_classfication == 'dp' || cost_classfication == 'am';
				// if (is_amdp) {
				// 	return true;
				// }
				// if (!rel_partner_ids || rel_partner_ids.length == 0) {
				// 	console.log(name + '无默认交易对象');
				// 	return false;
				// }
				return true;
				// if(rel_partner_ids.length == 1){
				//     return true;
				// }
				// if(rel_partner_ids.length>1){
				//     return false;
				// }
			}

		},
		methods: {
			init() {
				this.value = this.detail.cost_amount;
				this.textarea_value = this.detail.note ? this.detail.note : '';
				this.errorTip = ''
				this.set_ratio(this.detail.cost_amount);
			},
			set_ratio(num){
				if (!num && num<0) {
					this.detail.cost_ratio = 0;
					this.detail.month_cost_ratio = 0;
					return;
				}
				if (!this.day_sales_amount) {
					this.detail.cost_ratio = 0;
				} else {
					this.detail.cost_ratio = num / this.day_sales_amount;
				}
				if (!this.month_sales_amount) {
					this.detail.month_cost_ratio = 0;
				} else {
					this.detail.month_cost_ratio = (num+this.detail.month_cost_other_days) / this.month_sales_amount;
				}
			},
			openCostRecord() {
				let title = this.detail.cost_category_id[1];
				let list = JSON.parse(JSON.stringify(this.detail.list));
				let cate_cost_classfication = this.detail.cate_cost_classfication;
				let data = {
					title: title,
					classfication: cate_cost_classfication,
					category: JSON.parse(JSON.stringify(this.detail.cost_category_id)),
					readonly: this.readonly,
					list: list
				};
				let fn = (value) => {
					// console.log(value);
					this.detail.cost_amount = value.cost_amount;
					this.value = value.cost_amount;
					this.detail.list = value.list;
					this.$emit("updata",this.detail);
					// this.$set(this.qty,i,sales_qty);
					// this.save();
				};
				this.$emit("openCostRecord", data, fn.bind(this));
			},
			value_blur() {
				if ((this.value + '') == '') {
					let num = 0;
					this.value = num;
					// return;
				}
				if (Number(this.value) == this.detail.cost_amount) {
					// 没有修改
					return;
				}
				this.save();
			},
			value_input(e) {
				if(this.value+'' != ''){
					let num = Number(this.value);
					this.value = num;
				}
			},
			textarea_value_blur() {
				if (!this.textarea_value && !this.detail.note) {
					// 没有修改
					return;
				}
				if (this.textarea_value == this.detail.note) {
					// 没有修改
					return;
				}
				this.save();
			},
			save() {
				if (this.errorTip) {
					uni.$u.toast('请填写正确的金额。');
					return;
				}
				let item;
				if(!this.detail.list[0]){
					let cost_classfication = 'manual_input';
					let cate_cost_classfication = this.detail.cate_cost_classfication;
					console.log(cate_cost_classfication);
					if(cate_cost_classfication == 'am'){
						cost_classfication = 'am';
					}
					if(cate_cost_classfication == 'dp'){
						cost_classfication = 'dp';
					}
					item = {
						cost_category_id: this.detail.cost_category_id,
						cost_classfication:cost_classfication
					};
					this.$emit('add',item);
				}else{
					item = JSON.parse(JSON.stringify(this.detail.list[0]));
				}
				if (item.cost_classfication == 'am' || item.cost_classfication == 'dp') {
					item.amdp_amount = Number(this.value);
				} else if (item.cost_classfication == 'manual_input') {
					item.cost_amount = Number(this.value);
				}
				let obj_item = {
					...item,
					cost_category_id: item.cost_category_id[0],
					cost_obj_id: item.cost_obj_id[0] || 0,
					rel_partner_id: item.rel_partner_id[0] || 0,
					cost_center_id:item.cost_center_id[0]||0
				};
				let vals = {
					cost_category_id: this.detail.id,
					date: this.date,
					obj_list: [obj_item],
					unlink_ids: []
				};
				this.loading = true;
				let cost_amount_sum = Number(this.value);
				update_cost_report_data({
					vals: vals
				}, {
					custom: {
						catch: true
					}
				}).then((res) => {
					res.result.forEach((v, i) => {
						item.id = v.id;
					})
					this.detail.list = [item];
					this.detail.cost_amount = cost_amount_sum;
					this.$emit("updata",this.detail);
				}).catch(() => {
					this.value = this.detail.cost_amount;
				}).finally(() => {
					setTimeout(() => {
						this.loading = false;
					}, 500)
				})
			},
			// 弃用
			save_bak() {
				if (this.errorTip) {
					uni.$u.toast('请填写正确的金额。');
					return;
				}

				let data = {};
				data.id = this.detail.id;
				data.cost_amount = Number(this.value);
				data.note = this.textarea_value ? this.textarea_value : false;
				data.cost_category_id = this.detail.cost_category_id[0];
				data.cost_center_id = this.detail.cost_center_id[0];

				this.loading = true;

				if ((data.id + '').startsWith('virtual')) {
					common_create({
						model_name: this.modelname, //
						vals_list: [data]
					}, {
						custom: {
							catch: true
						}
					}).then((res) => {
						let newId = res.result[data.id].id;
						this.detail.id = newId;
						this.detail.cost_amount = data.cost_amount;
						this.detail.note = data.note;
					}).catch((res) => {
						// this.resetItem(i);
						this.value = this.detail.cost_amount;
						this.textarea_value = this.detail.note ? this.detail.note : '';
					}).finally(() => {
						// console.log('finally');
						setTimeout(() => {
							this.loading = false;
						}, 1000)
					})
				} else {
					common_write({
						model_name: this.modelname,
						vals_list: [data]
					}, {
						custom: {
							catch: true
						}
					}).then((res) => {
						this.detail.cost_amount = data.cost_amount;
						this.detail.note = data.note;
					}).catch(() => {
						// this.resetItem(i);
						this.value = this.detail.cost_amount;
						this.textarea_value = this.detail.note ? this.detail.note : '';
					}).finally(() => {
						setTimeout(() => {
							this.loading = false;
						}, 1000)
					})
				}
			},
			bindDel() {
				let name = this.detail.cost_category_id[1];
				this.$store.dispatch('modal', '确认删除【' + name + '】?').then(() => {
					this.del();
				})
			},
			del() {
				let id = this.detail.id;
				if ((id + '').startsWith('virtual')) {
					this.$emit("del", this.detail);
					return;
				}
				this.loading = true;
				common_delete({
					model_name: this.modelname,
					ids: [id]
				}, {
					custom: {
						catch: true
					}
				}).then((res) => {
					this.$emit("del", this.detail);
				}).catch(() => {

				}).finally(() => {
					setTimeout(() => {
						this.loading = false;
					}, 1000)
				})
			},
			confirm() {
				this.show = !this.show;
				this.info = this.textarea_value;
			},
			value_change() {

			},
			price_change() {

			},
			toggle(time_i) {
				this.show = !this.show;
			},
		}

	}
</script>

<style>
	.list-btn {
		background-color: #f5f5f5;
		padding: 6upx;
	}
</style>